package com.solocredit.finance.ui.main.impl

import android.Manifest
import android.content.Context
import com.solocredit.finance.app.MyApp
import com.solocredit.finance.base.utils.permission.XXPermissions
import com.solocredit.finance.config.MullaConfigs
import com.solocredit.finance.http.IHttpCallback
import com.solocredit.finance.mvp.presenter.MvpPresenter
import com.solocredit.finance.ui.main.view.IMullaHomeView
import com.solocredit.finance.utils.event.MullaEventData
import com.solocredit.finance.utils.helper.SharedHelper
import org.json.JSONArray
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/26 15:46
 * @Annotation：主页 Presenter 实现
 */
class MullaHomePresenterImpl(context: Context?) : MvpPresenter<IMullaHomeView>(context) {

    private var model: MullaHomeModelImpl? = null
    init {
        model = MullaHomeModelImpl()
    }
    /**
     * 是否是可申请列表
     */
    private var isApply = true

    /**
     * 点击的产品信息
     */
    private var selectProduct: JSONObject? = null

    /**
     * 切换列表类型
     */
    fun checkMullaProductStatus(isApply: Boolean){
        this.isApply = isApply
        when(isApply){
            true -> {//可申请产品列表
                mvpView?.showMullaProductsView()
            }
            else -> {//所有商品列表
                mvpView?.showMullaAppliedViews()
            }
        }
        MyApp.app.publisher.publish(MullaEventData(MullaEventData.TYPE.MULLA_PRODUCT_REFRESH))
        loadMullaProductListAction()
    }

    /**
     * 设置选择的产品信息
     */
    fun onMullaSetSelectProductInfo(item: JSONObject){
        selectProduct = item
    }

    /**
     * 加载产品表
     */
    fun loadMullaProductListAction(){
        val pData = SharedHelper.getMullaSPString(SharedHelper.MULLA_SPKEY.MULLA_PRODCTS)
        val pList = ArrayList<JSONObject>()
        if (pData.isNotEmpty()){
            val objArray = JSONArray(pData)
            for (i in 0..<objArray.length()){
                val item = objArray.optJSONObject(i)
                item.put("isApply",isApply)
                val status = item.optString("status")
                //可申请列表
                if (isApply && status == "APPLY"){
                    pList.add(item)
                    continue
                }
                //审核中、放款中、已拒绝
                if (!isApply && status != "APPLY" && status != "REPAYMENT"){
                    pList.add(item)
                }
            }
        }
        //设置产品列表
        mvpView?.showMullaProductsList(isApply,pList)
    }

    /**
     * 复制主产品信息到目标产品
     */
    private fun onMullaCopyMainProductToChildProductAction(targetProduct: String){
        model?.onMullaCopyMainProductToChildProductAction(targetProduct,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj")
                        var pToken = ""
                        if (obj != null){
                            pToken = obj.optString("token","")
                        }
                        selectProduct?.let {
                            if (pToken.isEmpty()){
                                pToken = it.optString("token")
                            }
                            val pName = it.optString("product")
                            mvpView?.showMullaLoanApplyPage(pName,pToken)
                        }
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView?.showMullaToast(msg)
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
                //是否是网络异常
                val errorCode = error.optInt("errorCode",0)
                if (isNetworkError(errorCode)){
                    mvpView?.showFlexiMolaNetworkErrorDialog("Mian Page CopyToApply", onRetryClick = {
                        mvpView?.showMullaLoading()
                        onMullaCopyMainProductToChildProductAction(targetProduct)
                    })
                    return
                }
                mvpView?.showMullaToast(error.optString("errorMsg"))
            }
            override fun onRequestFinish() {
                mvpView?.hideMullaLoading()
            }
        })
    }

    /**
     * 检查权限是否全部申请
     */
    fun checkMullaAllPermissionsAgree(){
        mvpView?.getContext()?.let {
            //权限列表未操作 -> 进入权限列表
            val perListStatus = SharedHelper.getMullaSPInt(SharedHelper.MULLA_SPKEY.MULLA_PERMISSION_LIST_STATUS)
            if (perListStatus == 0){
                mvpView?.showFlexiMolaPermissionList()
                return
            }
            //是否是广告渠道
            val isAdSource = SharedHelper.getMullaSPBoolean(SharedHelper.MULLA_SPKEY.MULLA_IS_ADSOURCE)
            //广告渠道 && 权限列表未同意 -> 进入权限列表
            if (isAdSource && perListStatus == -1){
                mvpView?.showFlexiMolaPermissionList()
                return
            }
            //广告渠道 && 未同意sms权限 -> 进入权限列表
            if (isAdSource && !XXPermissions.isGranted(it, Manifest.permission.READ_SMS)){
                mvpView?.showFlexiMolaPermissionList()
                return
            }
            mvpView?.showMullaCheckPermissionSuccess()
        }
    }

    /**
     * 验证认证流程是否完成
     */
    fun checkMullaAllStepsAction(){
        mvpView?.showMullaLoading()
        // TODO: 此处需要验证流程
        val stepString = SharedHelper.getMullaSPString(SharedHelper.MULLA_SPKEY.MULLA_PROCESS)
        if (stepString.isEmpty()){
            //通知刷新总流程
            MyApp.app.publisher.publish(MullaEventData(MullaEventData.TYPE.MULLA_PROCESS_REFRESH))
            return
        }
        if (stepString.isNotEmpty()){
            //记录点击的产品信息，适用于申贷之后直接进入详情
            selectProduct?.let {
                MullaConfigs.clickProductLogo = it.optString("logo")
                MullaConfigs.clickProductName = it.optString("product")
                MullaConfigs.clickProductToken = it.optString("token")
                MullaConfigs.clickProductTitle = it.optString("name")
            }

            val stepData = JSONObject(stepString)
            if (stepData.optJSONArray("steps")?.length() == 0){//流程已完成 - 进入申贷确认页
                selectProduct?.let {
                    val pName = it.optString("product")
                    val pToken = it.optString("token")
                    //非主产品
                    if (pName != MullaConfigs.MULLA_APPNAME){
                        //copy 主产品信息到子产品
                        onMullaCopyMainProductToChildProductAction(pName)
                    } else {
                        //主产品进入申待确认页
                        mvpView?.showMullaLoanApplyPage(pName,pToken)
                    }
                }
            } else {//流程未完成 - 进入 认证步骤页面
                mvpView?.showMullaProcessStepsPage()
            }
        }
    }

    /**
     * 获取当前是可申请或已申请列表
     */
    fun isApply(): Boolean{
        return this.isApply
    }
}